package com.akkainaction.tool.io.tcp.server;

import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.io.Tcp;
import akka.io.TcpMessage;

import java.net.InetSocketAddress;

public class TcpServerDemo extends UntypedActor {

    @Override
    public void preStart() throws Exception {
        super.preStart();
        ActorRef tcpManager = Tcp.get(getContext().system()).manager();
        tcpManager.tell(TcpMessage.bind(getSelf(), new InetSocketAddress("127.0.0.1", 1234), 100), getSelf());
    }

    @Override
    public void onReceive(Object msg) throws Exception {
        if (msg instanceof Tcp.Bound) {
            Tcp.Bound bound = (Tcp.Bound) msg;
            System.out.println("bound:" + bound);
        } else if (msg instanceof Tcp.Connected) {
            Tcp.Connected conn = (Tcp.Connected) msg;
            System.out.println("conn:" + conn);
            ActorRef handler = getContext().actorOf(Props.create(ServerHandler.class));
            getSender().tell(TcpMessage.register(handler), getSelf());
        }
    }
}
